import 'package:safetymonitor/app/components/custom_modele/custom_file_upload_page.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_multiple_bottom_sheet.dart';
import 'package:safetymonitor/app/components/custom_refresh.dart';
import 'package:safetymonitor/app/components/dialog/risk_custom_callback_general_dialog.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/entities/application/corporation_name_entity.dart';
import 'package:safetymonitor/app/data/entities/application/security_control_promise_entity.dart';
import 'package:safetymonitor/modules/home/home_page/home_page_control.dart';

class RiskCommitmentController extends GetxController {
  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  // 公司列表
  List<CorporationNameEntity> nameList = [];

  ///选择的公司
  String selectCompany = '';

  ///主公司 写死（默认）
  String currentMainCompany = '金钼集团';

  // 选中的公司
  CorporationNameEntity? _selectId;

  ///获取账号的当前公司名字
  String? userCompanyName;

  /// 风险承诺的添加
  List<String> riskSecurityPromiseAdd = [];

  @override
  void onInit() {
    super.onInit();
    userCompanyName = UserManager.getUserCompanyName() ?? '';
    nameList = Get.find<HomePageControl>().nameList;
    if (currentMainCompany == userCompanyName && nameList.isNotEmpty) {
      //只有是主公司才才取第一个 并获取数据
      _selectId = nameList.first;
      selectCompany = getString();
    }
  }
  bool isNotPermissions=true;
  /// 获取数据
  Future<List<SecurityControlPromiseEntity>> getRiskSecurityPromise(
      int index, int size,
      {String? search}) async {
    final res =
        await HttpUtil().generateGetRequest<List<SecurityControlPromiseEntity>>(
      Interface.getRiskSecurityPromise,
      queryParameters: {
        'pageNo': index,
        'pageSize': size,
        'companyId':currentMainCompany == userCompanyName?_selectId?.id:UserManager.getUserCompanyId(),
      },
    ).execute();
    List<SecurityControlPromiseEntity>? list = [];
    res.onSuccess((result) {
      if (result.data != null) {
        list = result.data;
      }
      isNotPermissions=true;
      update();
    });
    res.onError((result) {
      if(result.code==403&&result.message=='没有该操作权限'){
        isNotPermissions=false;
        update();
      }
    });
    return list ?? [];
  }

  // 选取公司
  void selectCompanyOn() {
    CustomEquipmentBottomSheet<CorporationNameEntity>(
      dataList: nameList,
      checkedList: _selectId != null ? [_selectId!] : [],
      onConfirm: (value) {
        if (value.isNotEmpty) {
          _selectId = value[0];
          selectCompany = getString();
          globalKey.currentState?.onRefresh();
          update();
        }
      },
      title: '选择公司',
      isMultiple: false,
    ).showBottomSheetDialog();
  }

  String getString() {
    if (_selectId != null) {
      return _selectId!.name!.trim();
    }
    return '公司名';
  }

  ///新增
  void addRiskSecurityPromise() {
    Get.dialog<bool>(
      CustomGeneralCallbackDialog(
        title: '上传企业风险承诺',
        content: CustomFileUploadPage(
          isRequired: false,
          isShowDivider: false,
          isFirst: true,
          splitCommaInUrl: true,
          title: '附件',
          onCallBack: (value) {
            riskSecurityPromiseAdd = value;
          },
        ),
        onPressed: uploadRiskSecurityPromise,
      ),
    );
  }

  /// 上传企业风险承诺
  void uploadRiskSecurityPromise() async {
    if (riskSecurityPromiseAdd.isEmpty) {
      AppToast.showWarning('请上传文件');
      return;
    }
    final res = await HttpUtil().generatePostRequest(
      Interface.uploadRiskSecurityPromise,
      data: {
        'path': riskSecurityPromiseAdd.first,
      },
    ).execute();
    res.onSuccess((result) {
      Get.back();
      AppToast.showSuccess(result.message);
      globalKey.currentState?.onRefresh();
    });
  }
}
